from flask import render_template, current_app, request, jsonify
from info import redis_store, constants
from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blu
from flask import session


@index_blu.route("/")
def index():
    """获取用户登录信息 若用户已登录，将登录信息传到模板中供模板显示"""

    # 获取session中的用户id
    user_id = session.get('user_id', None)
    # 根据获取的用户id，在数据库中查询对应用户信息
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as a:
            current_app.logger.error(a)

    #  右侧新闻排行逻辑
    # 按照点击量排序，查询出前6个
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as a :
        current_app.logger.error(a)
    # 按照查询取出的是news对象，进一步遍历对象，将对象的字典添加至字典列表中
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    # 获取首页所有分类
    categories = Category.query.all()
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    data = {
        'user': user.to_dict() if user else None,
        'news_dict_list': news_dict_list,
        "category_list":category_list
    }

    return render_template('news/index.html', data=data)


# 在打开网页时，浏览器会默认请求根目录+favicon.ico路径作为网站的小图标
# 加载网页图标
@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


# 新闻首页列表数据展示
@index_blu.route('/news_list')
def news_list():
    """列表形式展示首页新闻"""
    # 1、获取参数
    # 新闻分类id
    cid = request.args.get('cid','1')
    page =request.args.get('page','1')
    per_page =request.args.get('per_page', constants.HOME_PAGE_MAX_NEWS)
    # 2、校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno = RET.PARAMERR,errmsg='参数错误')

    filters = [News.status==0]  # 显示审核通过的新闻
    if cid != 1:
        filters.append(News.category_id == cid)
    paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    total_page = paginate.pages
    current_page = paginate.page
    news_li = paginate.items # 模型对象
    news_dict = []
    for news in news_li:
        news_dict.append(news.to_basic_dict())
    data = {
        "total_page" : total_page,
        "current_page":current_page,
        "news_dict":news_dict
    }
    return jsonify(errno=RET.OK,errmsg='ok',data=data)